package com.flyou.ccnucenter.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
/**
 * ============================================================  
* 项目名称：androidTools   
* 
* 类名称：SmsUtils   
* 
* 类描述：   短信的备份与还原
* 
* 创建人：flyou  
* 
* 创建时间：2015-3-31 下午12:17:57  
*  
* 修改备注：   
* 
* 版本：@version    
*   ============================================================
 */
public class SmsUtils {
  private static final String TAG = "SmsUtils";
  private static ContentResolver resolver;
  private static Uri url;
  private static ContentValues values;
  private static ProgressDialog dialog;
  private static int max;
  private static int size;

  public interface BackUpCallBack {
    /**
     * 开始备份的时候，设置进度的最大值
     * 
     * @param max
     *          总进度
     */
    public void beforeBackup(int max);

    /**
     * 备份过程中，增加进度
     * 
     * @param progress
     *          当前进度
     */
    public void onSmsBackup(int progress);

  }

  public interface ReStroeCallBack {
    /**
     * 恢复短信前
     * 
     * @param max
     *          最大短信条数
     */
    public void beforeReStore(int max);

    /**
     * 恢复短息时
     * 
     * @param position
     *          当前进度
     */
    public void OnReStore(int position);

  }

  /**
   * 
   * @param context
   *          上下文
   * @throws Exception
   *           把异常抛出给调用处处理
   */
  public static void buckUpSms(Context context, BackUpCallBack callBack) throws Exception {

    resolver = context.getContentResolver();
    File file = new File(Environment.getExternalStorageDirectory(), "backUpSms.xml");
    FileOutputStream fos = new FileOutputStream(file);
    XmlSerializer serializer = Xml.newSerializer();
    serializer.setOutput(fos, "utf-8");
    serializer.startDocument("utf-8", true);
    serializer.startTag(null, "smss");
    url = Uri.parse("content://sms/");
    Cursor cursor = resolver.query(url, new String[] { "address", "date", "type", "body" }, null, null, null);
    // 操作前
    callBack.beforeBackup(cursor.getCount());
    int postion = 0;

    // 遍历cursor 序列化 短信实体
    serializer.attribute(null, "size", cursor.getCount() + "");
    while (cursor.moveToNext()) {
      Thread.sleep(300);
      String address = cursor.getString(0);
      String date = cursor.getString(1);
      String type = cursor.getString(2);
      String body = cursor.getString(3);

      serializer.startTag(null, "sms");

      serializer.startTag(null, "address");
      serializer.text(address);
      serializer.endTag(null, "address");

      serializer.startTag(null, "date");
      serializer.text(date);
      serializer.endTag(null, "date");

      serializer.startTag(null, "type");
      serializer.text(type);
      serializer.endTag(null, "type");

      serializer.startTag(null, "body");
      serializer.text(body);
      serializer.endTag(null, "body");

      serializer.endTag(null, "sms");
      // 更新进度条
      callBack.onSmsBackup(postion++);
    }
    cursor.close();
    serializer.endTag(null, "smss");
    serializer.endDocument();
    fos.close();
  }

  /**
   * 短信的还原
   */
  public static void reStoreSms(Context context, ReStroeCallBack callBack) throws Exception {
    resolver = context.getContentResolver();

    // 删除原有短信数据
    Cursor cursor = resolver.query(url, new String[] { "address", "date", "type", "body" }, null, null, null);
    if (cursor.moveToNext()) {
      resolver.delete(url, null, null);
    }
    cursor.close();
    
    // 获取短信备份文件
    File file = new File(Environment.getExternalStorageDirectory(), "backUpSms.xml");
    InputStream inputStream = new FileInputStream(file);
    // 创建解析对象
    XmlPullParser parser = Xml.newPullParser();
    parser.setInput(inputStream, "utf-8");

    int eventType = parser.getEventType();

    while (eventType != XmlPullParser.END_DOCUMENT) {
      String tagName = parser.getName();
      switch (eventType) {
        case XmlPullParser.START_TAG:
          if ("smss".equals(tagName)) {

            max = Integer.parseInt(parser.getAttributeValue(null, "size"));
            Log.i(TAG, max + "-----------------------");
            // 备份前 设置最大进度条值
            callBack.beforeReStore(max);

            size = Integer.parseInt(parser.getAttributeValue(null, "size"));
          } else if ("sms".equals(tagName)) {
            values = new ContentValues();
          } else if ("address".equals(tagName)) {
            values.put("address", parser.nextText());
          } else if ("date".equals(tagName)) {
            values.put("date", parser.nextText());

          } else if ("type".equals(tagName)) {
            values.put("type", parser.nextText());

          } else if ("body".equals(tagName)) {
            values.put("body", parser.nextText());

          }
          break;
        case XmlPullParser.END_TAG:
          // 插入短信数据
          if ("sms".equals(tagName)) {
            Log.i(TAG, "----------------插入数据---------------");
            resolver.insert(url, values);

            callBack.OnReStore(size - (max--));
            Thread.sleep(300);
          }
          break;
        default:
          break;

      }
      // 获得下一个标签名
      eventType = parser.next();
    }

  }
}
